import type { StateCreator } from 'zustand';
import type { AgentsStore } from '../index';

// 文件信息接口
export interface FileInfo {
  id: string;
  name: string;
  path: string;
  size: number;
  type: string;
  lastModified: number;
  content?: string; // 可选，用于存储文件内容
}

// 联网搜索设置
export interface WebSearchSettings {
  enabled: boolean;
  provider: 'google' | 'bing' | 'duckduckgo';
  maxResults: number;
  timeout: number; // 毫秒
}

// Agents设置接口
export interface AgentsSettings {
  webSearch: WebSearchSettings;
  fileSelection: {
    maxFiles: number;
    allowedTypes: string[];
    maxFileSize: number; // 字节
  };
  ui: {
    showFilePreview: boolean;
    compactMode: boolean;
  };
}

// Agents状态接口
export interface AgentsState {
  // 联网搜索功能
  webSearchEnabled: boolean;
  webSearchSettings: WebSearchSettings;
  
  // 文件选择功能
  selectedFiles: FileInfo[];
  maxSelectedFiles: number;
  
  // 应用设置
  settings: AgentsSettings;
  
  // 状态管理
  isSettingsLoaded: boolean;
  settingsVersion: number;
}

// Agents Actions接口
export interface AgentsActions {
  // 联网搜索功能
  setWebSearchEnabled: (enabled: boolean) => void;
  updateWebSearchSettings: (settings: Partial<WebSearchSettings>) => void;
  toggleWebSearch: () => void;
  
  // 文件选择功能
  addSelectedFile: (file: FileInfo) => void;
  removeSelectedFile: (fileId: string) => void;
  clearSelectedFiles: () => void;
  updateSelectedFile: (fileId: string, updates: Partial<FileInfo>) => void;
  setSelectedFiles: (files: FileInfo[]) => void;
  
  // 设置管理
  updateSettings: (settings: Partial<AgentsSettings>) => void;
  updateSetting: <K extends keyof AgentsSettings>(
    key: K, 
    value: AgentsSettings[K]
  ) => void;
  resetSettings: () => void;
  
  // 状态管理
  setSettingsLoaded: (loaded: boolean) => void;
  incrementSettingsVersion: () => void;
  loadSettings: () => Promise<void>;
  saveSettings: () => Promise<void>;
  exportSettings: () => string;
  importSettings: (settingsJson: string) => boolean;
}

// Agents Slice类型
export type AgentsSettingsSlice = AgentsState & AgentsActions;

// 默认联网搜索设置
const defaultWebSearchSettings: WebSearchSettings = {
  enabled: false,
  provider: 'google',
  maxResults: 10,
  timeout: 5000,
};

// 默认Agents设置
const defaultAgentsSettings: AgentsSettings = {
  webSearch: defaultWebSearchSettings,
  fileSelection: {
    maxFiles: 10,
    allowedTypes: ['.txt', '.md', '.js', '.ts', '.tsx', '.jsx', '.json', '.xml', '.html', '.css'],
    maxFileSize: 10 * 1024 * 1024, // 10MB
  },
  ui: {
    showFilePreview: true,
    compactMode: false,
  },
};

// 默认状态
const initialAgentsState: AgentsState = {
  webSearchEnabled: false,
  webSearchSettings: defaultWebSearchSettings,
  selectedFiles: [],
  maxSelectedFiles: 10,
  settings: defaultAgentsSettings,
  isSettingsLoaded: false,
  settingsVersion: 1,
};

// 创建Agents设置Slice
export const createAgentsSettingsSlice: StateCreator<
  AgentsStore,
  [['zustand/immer', never], ['zustand/devtools', never], ['zustand/persist', unknown], ['zustand/subscribeWithSelector', never]],
  [],
  AgentsSettingsSlice
> = (set, get) => ({
  // 初始状态
  ...initialAgentsState,

  // 联网搜索功能Actions
  setWebSearchEnabled: (enabled) => {
    set((state: AgentsStore) => {
      state.webSearchEnabled = enabled;
      state.webSearchSettings.enabled = enabled;
    });
  },

  updateWebSearchSettings: (settings) => {
    set((state: AgentsStore) => {
      state.webSearchSettings = { ...state.webSearchSettings, ...settings };
      if (settings.enabled !== undefined) {
        state.webSearchEnabled = settings.enabled;
      }
    });
  },

  toggleWebSearch: () => {
    set((state: AgentsStore) => {
      state.webSearchEnabled = !state.webSearchEnabled;
      state.webSearchSettings.enabled = state.webSearchEnabled;
    });
  },

  // 文件选择功能Actions
  addSelectedFile: (file) => {
    set((state: AgentsStore) => {
      const existingIndex = state.selectedFiles.findIndex((f: FileInfo) => f.id === file.id);
      if (existingIndex === -1 && state.selectedFiles.length < state.maxSelectedFiles) {
        state.selectedFiles.push(file);
      }
    });
  },

  removeSelectedFile: (fileId) => {
    set((state: AgentsStore) => {
      state.selectedFiles = state.selectedFiles.filter((file: FileInfo) => file.id !== fileId);
    });
  },

  clearSelectedFiles: () => {
    set((state: AgentsStore) => {
      state.selectedFiles = [];
    });
  },

  updateSelectedFile: (fileId, updates) => {
    set((state: AgentsStore) => {
      const fileIndex = state.selectedFiles.findIndex((f: FileInfo) => f.id === fileId);
      if (fileIndex !== -1) {
        state.selectedFiles[fileIndex] = { ...state.selectedFiles[fileIndex], ...updates };
      }
    });
  },

  setSelectedFiles: (files) => {
    set((state: AgentsStore) => {
      state.selectedFiles = files.slice(0, state.maxSelectedFiles);
    });
  },

  // 设置管理Actions
  updateSettings: (settings) => {
    set((state: AgentsStore) => {
      state.settings = { ...state.settings, ...settings };
    });
  },

  updateSetting: (key, value) => {
    set((state: AgentsStore) => {
      state.settings[key] = value;
    });
  },

  resetSettings: () => {
    set((state: AgentsStore) => {
      state.settings = { ...defaultAgentsSettings };
      state.webSearchEnabled = defaultWebSearchSettings.enabled;
      state.webSearchSettings = { ...defaultWebSearchSettings };
      state.maxSelectedFiles = defaultAgentsSettings.fileSelection.maxFiles;
    });
  },

  // 状态管理Actions
  setSettingsLoaded: (loaded) => {
    set((state: AgentsStore) => {
      state.isSettingsLoaded = loaded;
    });
  },

  incrementSettingsVersion: () => {
    set((state: AgentsStore) => {
      state.settingsVersion += 1;
    });
  },

  loadSettings: async () => {
    try {
      const stored = localStorage.getItem('agents-settings');
      if (stored) {
        const parsedSettings = JSON.parse(stored);
        set((state: AgentsStore) => {
          state.settings = { ...defaultAgentsSettings, ...parsedSettings.settings };
          state.webSearchEnabled = parsedSettings.webSearchEnabled ?? defaultWebSearchSettings.enabled;
          state.webSearchSettings = { ...defaultWebSearchSettings, ...parsedSettings.webSearchSettings };
          state.maxSelectedFiles = parsedSettings.maxSelectedFiles ?? defaultAgentsSettings.fileSelection.maxFiles;
          state.isSettingsLoaded = true;
        });
      } else {
        set((state: AgentsStore) => {
          state.isSettingsLoaded = true;
        });
      }
    } catch (error) {
      console.error('Failed to load agents settings:', error);
      set((state: AgentsStore) => {
        state.isSettingsLoaded = true;
      });
    }
  },

  saveSettings: async () => {
    try {
      const currentState = get();
      const settingsToSave = {
        settings: currentState.settings,
        webSearchEnabled: currentState.webSearchEnabled,
        webSearchSettings: currentState.webSearchSettings,
        maxSelectedFiles: currentState.maxSelectedFiles,
        version: currentState.settingsVersion,
      };
      localStorage.setItem('agents-settings', JSON.stringify(settingsToSave));
    } catch (error) {
      console.error('Failed to save agents settings:', error);
    }
  },

  exportSettings: () => {
    const currentState = get();
    const exportData = {
      settings: currentState.settings,
      webSearchEnabled: currentState.webSearchEnabled,
      webSearchSettings: currentState.webSearchSettings,
      maxSelectedFiles: currentState.maxSelectedFiles,
      version: currentState.settingsVersion,
      exportedAt: new Date().toISOString(),
    };
    return JSON.stringify(exportData, null, 2);
  },

  importSettings: (settingsJson) => {
    try {
      const importedData = JSON.parse(settingsJson);
      if (importedData.settings) {
        set((state: AgentsStore) => {
          state.settings = { ...defaultAgentsSettings, ...importedData.settings };
          state.webSearchEnabled = importedData.webSearchEnabled ?? defaultWebSearchSettings.enabled;
          state.webSearchSettings = { ...defaultWebSearchSettings, ...importedData.webSearchSettings };
          state.maxSelectedFiles = importedData.maxSelectedFiles ?? defaultAgentsSettings.fileSelection.maxFiles;
          state.settingsVersion = importedData.version || state.settingsVersion + 1;
        });
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to import agents settings:', error);
      return false;
    }
  },
}); 